package qiyeweixin

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
)

type QiyeWeixinToken struct {
	ErrCode     int64  `json:"errcode"`
	ErrMsg      string `json:"errmsg"`
	AccessToken string `json:"access_token"`
	ExpiresIn   int64  `json:"expires_in"`
}

func GetAccessToken() (accessToken string, errR error) {
	resp, err := http.Get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww22dc35c5ba8e0210&corpsecret=xNtgDny_MQzUP4Sz8eGHGlhHY7SNlMK1PG8Gva17spA")
	if err != nil {
		log.Fatal(err)
		errR = err
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	log.Println("resp.StatusCode", resp.StatusCode)
	if resp.StatusCode == 200 {
		log.Println("GetAccessToken ok")
	}

	log.Println(string(body))

	qiyeWeixinToken := QiyeWeixinToken{}

	err = json.Unmarshal([]byte(string(body)), &qiyeWeixinToken)
	if err != nil {
		log.Fatalln(err)
		errR = err
		return
	}

	accessToken = qiyeWeixinToken.AccessToken

	return
}

func SendMessage(content string, accessToken string) error {
	paramMap := make(map[string]interface{})
	paramMap["totag"] = "8"
	paramMap["msgtype"] = "text"
	paramMap["agentid"] = "1000015"
	textMap := make(map[string]interface{})
	textMap["content"] = content
	paramMap["text"] = textMap
	paramMap["safe"] = 0
	sendUrl := "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken
	bytesData, _ := json.Marshal(paramMap)
	resp, _ := http.Post(sendUrl, "application/json", bytes.NewReader(bytesData))
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	log.Println(string(body))
	return nil
}
